/*
 * @Author: 涵崽
 * @Date: 2023-10-23 15:18:58
 * @email: 1045654@qq.com
 * @gitee: https://gitee.com/han-zai
 * @LastEditors: 涵崽
 * @LastEditTime: 2024-06-14 15:14:00
 * @Description: 微信：1045654
 */
// 导出一个对象，该对象拥有get与post方法用于发送相应类型的请求
import qs from "qs";
import axios from "axios";
import router from "@/router";
// import { removeToken, removeRoles } from "@/utils/auth";
import {
  RSAencrypt,
  RSAdecrypt,
  AESencrypt,
  AESdecrypt,
  generateRandomString,
} from "@/utils/rsa";
import { getToken, removeToken, getAxiosLang } from "@/utils/auth";
import { Message, Loading } from "element-ui";
const instance = axios.create();
let loadingInstance;
instance.interceptors.request.use(
  (config) => {
    if (!config.data.isLoading) {
      loadingInstance = Loading.service({
        //加载loading
        fullscreen: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
    }

    if (getToken()) {
      config.headers["token"] = getToken();
    }
    config.headers["Lang"] = getAxiosLang();
    config.headers["Content-Type"] = "application/json";
    return config;
  },
  (error) => {
    // 处理请求错误
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    if (loadingInstance) loadingInstance.close();
    // 拦截成功响应
    const { data } = response;
    if (data.code === 10086) {
      Message({
        message: data.msg,
        type: "info",
        duration: 5 * 1000,
      });
      removeToken();
      router.push("/login");
    } else if (data.code == 2001) {
      Message({
        message: data.msg,
        type: "warning",
      });
    } else if (data.code !== 200) {
      Message({
        message: data.msg,
        type: "warning",
      });
    }
    return response.data;
  },
  (error) => {
    if (loadingInstance) loadingInstance.close(); // 请求成功时关闭加载指示器
    Message({
      message: `服务器报错了：${error.message}！请联系系统管理员`,
      type: "error",
    });
    // 拦截错误响应
    return Promise.reject(error);
  }
);

const myaxios = {
  /**
   * 用于发送 get 请求
   * @param {string} url 请求路径
   * @param {object} params 请求参数对象  {参数名:参数值}
   */
  get(url, params) {
    return instance({
      url,
      method: "GET",
      params,
    });
  },

  /**
   * 用于发送 post 请求
   * @param {string} url 请求路径
   * @param {object} data 请求参数对象  {参数名:参数值}
   */
  post(url, data) {
    return instance({
      url,
      method: "POST",
      // data: qs.stringify(data),
      data,
    });
  },
  postEncrypt(url, data) {
    let key = generateRandomString(16); // 生成16位随机字符串
    let encryptedKey = RSAencrypt(key); // 对字符串加密
    let ciphertext = AESencrypt(key, data.data); //AES对data加密
    data.data = ciphertext;
    data.sign = encryptedKey;
    return instance({
      url,
      method: "POST",
      data,
      // data,
    });
  },
};

export default myaxios;
